<template>
	<div class="handwriting">
		<canvas ref="canvas" @touchstart="startDraw" @touchmove="drawing" @touchend="stopDraw" />
	</div>
</template>

<script>
	export default {
		name: 'handwriting',
		data() {
			return {
				ctx: null,
				canvasWidth: 0,
				canvasHeight: 0,
				lastX: 0,
				lastY: 0,
				isDrawing: false
			}
		},
		mounted() {
			this.initCanvas()
		},
		methods: {
			initCanvas() {
				// 初始化画布
				const canvas = this.$refs.canvas
				this.ctx = canvas.getContext('2d')
				this.canvasWidth = canvas.width = canvas.offsetWidth
				this.canvasHeight = canvas.height = canvas.offsetHeight
				this.ctx.strokeStyle = '#000'
				this.ctx.lineJoin = 'round'
				this.ctx.lineWidth = 5
			},
			startDraw(e) {
				// 开始绘制
				const {
					clientX,
					clientY
				} = e.touches[0]
				this.lastX = clientX
				this.lastY = clientY
				this.isDrawing = true
			},
			drawing(e) {
				// 绘制中
				if (!this.isDrawing) return
				const {
					clientX,
					clientY
				} = e.touches[0]
				this.ctx.beginPath()
				this.ctx.moveTo(this.lastX, this.lastY)
				this.ctx.lineTo(clientX, clientY)
				this.ctx.closePath()
				this.ctx.stroke()
				this.lastX = clientX
				this.lastY = clientY
			},
			stopDraw() {
				// 停止绘制
				this.isDrawing = false
			},
			clearCanvas() {
				// 清空画布
				this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
			},
			saveImage() {
				// 保存签名图片
				const dataURL = this.$refs.canvas.toDataURL('image/png')
				console.log(dataURL)
			}
		}
	}
</script>

<style>
	.handwriting {
		width: 100%;
		height: 300px;
		position: relative;
	}

	canvas {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
	}
</style>